<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/base}">
<head>
    <title>购物车</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .cart-item-image {
            width: 100px;
            height: 100px;
            object-fit: cover;
        }
        .quantity-input {
            width: 80px;
        }
        .cart-summary {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
        }
    </style>
</head>
<body>
    <div layout:fragment="content">
        <div class="row mb-4">
            <div class="col">
                <h2>我的购物车</h2>
            </div>
        </div>

        <div class="row">
            <!-- 购物车列表 -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-body">
                        <!-- 空购物车提示 -->
                        <div th:if="${#lists.isEmpty(cartItems)}" class="text-center py-5">
                            <i class="fas fa-shopping-cart fa-3x text-muted mb-3"></i>
                            <h5>购物车是空的</h5>
                            <a th:href="@{/products}" class="btn btn-primary mt-3">
                                去逛逛
                            </a>
                        </div>

                        <!-- 购物车商品列表 -->
                        <div th:if="${not #lists.isEmpty(cartItems)}">
                            <div class="table-responsive">
                                <table class="table align-middle">
                                    <thead>
                                        <tr>
                                            <th>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" 
                                                           id="selectAll" onchange="toggleSelectAll()">
                                                </div>
                                            </th>
                                            <th>商品信息</th>
                                            <th>单价</th>
                                            <th>数量</th>
                                            <th>小计</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr th:each="item : ${cartItems}">
                                            <td>
                                                <div class="form-check">
                                                    <input class="form-check-input item-checkbox" 
                                                           type="checkbox" th:value="${item.id}"
                                                           onchange="updateTotal()">
                                                </div>
                                            </td>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <img th:src="${item.productImage ?: '/static/images/default-product.jpg'}"
                                                         class="cart-item-image me-3" alt="商品图片">
                                                    <div>
                                                        <h6 class="mb-1" th:text="${item.productName}">商品名称</h6>
                                                        <small class="text-muted" th:text="${item.specifications}">
                                                            商品规格
                                                        </small>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="text-danger" 
                                                      th:text="${'¥' + #numbers.formatDecimal(item.price, 1, 2)}">
                                                    ¥0.00
                                                </span>
                                            </td>
                                            <td>
                                                <div class="input-group quantity-input">
                                                    <button type="button" class="btn btn-outline-secondary"
                                                            th:onclick="'updateQuantity(' + ${item.id} + ', -1)'">-</button>
                                                    <input type="number" class="form-control text-center" 
                                                           th:value="${item.quantity}" min="1" 
                                                           th:max="${item.stock}"
                                                           th:onchange="'updateQuantity(' + ${item.id} + ', 0, this.value)'">
                                                    <button type="button" class="btn btn-outline-secondary"
                                                            th:onclick="'updateQuantity(' + ${item.id} + ', 1)'">+</button>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="text-danger fw-bold" 
                                                      th:text="${'¥' + #numbers.formatDecimal(item.price * item.quantity, 1, 2)}">
                                                    ¥0.00
                                                </span>
                                            </td>
                                            <td>
                                                <button class="btn btn-sm btn-outline-danger"
                                                        th:onclick="'removeItem(' + ${item.id} + ')'">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 结算信息 -->
            <div class="col-md-4">
                <div class="cart-summary">
                    <h5 class="mb-4">结算信息</h5>
                    <div class="d-flex justify-content-between mb-2">
                        <span>已选商品</span>
                        <span id="selectedCount">0</span>
                    </div>
                    <div class="d-flex justify-content-between mb-3">
                        <span>总计金额</span>
                        <span class="text-danger fw-bold" id="totalAmount">¥0.00</span>
                    </div>
                    <button class="btn btn-danger w-100" onclick="checkout()" 
                            th:disabled="${#lists.isEmpty(cartItems)}">
                        去结算
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script th:inline="javascript">
        function toggleSelectAll() {
            const selectAll = document.getElementById('selectAll');
            document.querySelectorAll('.item-checkbox').forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
            updateTotal();
        }

        function updateTotal() {
            const items = /*[[${cartItems}]]*/ [];
            let selectedCount = 0;
            let totalAmount = 0;

            document.querySelectorAll('.item-checkbox').forEach((checkbox, index) => {
                if (checkbox.checked) {
                    selectedCount++;
                    totalAmount += items[index].price * items[index].quantity;
                }
            });

            document.getElementById('selectedCount').textContent = selectedCount;
            document.getElementById('totalAmount').textContent = 
                '¥' + totalAmount.toFixed(2);
        }

        function updateQuantity(itemId, delta, value) {
            const quantity = value ? parseInt(value) : null;
            fetch(`/cart/update/${itemId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    delta: delta,
                    quantity: quantity
                })
            }).then(response => {
                if (response.ok) {
                    location.reload();
                }
            });
        }

        function removeItem(itemId) {
            if (confirm('确定要删除这件商品吗？')) {
                fetch(`/cart/remove/${itemId}`, {
                    method: 'POST'
                }).then(response => {
                    if (response.ok) {
                        location.reload();
                    }
                });
            }
        }

        function checkout() {
            const selectedItems = [];
            document.querySelectorAll('.item-checkbox').forEach((checkbox, index) => {
                if (checkbox.checked) {
                    selectedItems.push(checkbox.value);
                }
            });

            if (selectedItems.length === 0) {
                alert('请选择要结算的商品');
                return;
            }

            const form = document.createElement('form');
            form.method = 'POST';
            form.action = /*[[@{/orders/checkout}]]*/ '';

            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'items';
            input.value = selectedItems.join(',');
            form.appendChild(input);

            document.body.appendChild(form);
            form.submit();
        }
    </script>
</body>
</html> 